package com.uhylab.uhuvinetest.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.base.UHBaseActivity;
import com.uhylab.uhuvinetest.camera.CaptureActivity;
import com.uhylab.uhuvinetest.qrcamera.activity.ResultActivity;
import com.uhylab.uhuvinetest.view.VelocimeterView;

import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

public class UHPhotoActivity extends UHBaseActivity implements View.OnClickListener {
    private static final int REQUEST_SELECT_PICTURE = 0x01;
    private VelocimeterView mVelocimeterView;
    private ImageView iv_back;
    private TextView tv_jump;
    private Button history_img_button;
    private boolean handler_open = false;
    private float[] arrcolor = new float[48];
    static {
        System.loadLibrary("opencv_java3");
        System.loadLibrary("mixed_sample");
    }


    @Override
    public int bindLayout() {
        return R.layout.activity_photo;
    }

    @Override
    public void initView(View view) {
        mVelocimeterView = (VelocimeterView) findViewById(R.id.velocimeter);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_jump = (TextView) findViewById(R.id.tv_jump);
        history_img_button = (Button) findViewById(R.id.history_img_button);
    }

    @Override
    public void doBusiness(Context mContext) {
        mVelocimeterView.setValue(0);

        if (!handler_open) {
            handler.sendEmptyMessageDelayed(0, 1000);
            handler_open = true;
        }
        history_img_button.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        tv_jump.setOnClickListener(this);

    }

    @Override
    public void resume() {
        if (!handler_open) {
            handler.sendEmptyMessageDelayed(0, 1000);
            handler_open = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler_open) {
            handler.removeMessages(0);
            handler_open = false;
        }
    }

    @Override
    public void destroy() {
        if (handler_open) {
            handler.removeMessages(0);
            handler_open = false;
        }

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            float value = mVelocimeterView.getValue();
            value += 1;
            handler.sendEmptyMessageDelayed(0, 1000);
            if (value > mVelocimeterView.getMax()) {
                value = mVelocimeterView.getMax();
                handler.removeMessages(0);
                enterCaptureActivity();
            }
            mVelocimeterView.setValue(value);
        }
    };

    private void enterCaptureActivity() {
        Intent intent = new Intent();
        intent.setClass(UHPhotoActivity.this, CaptureActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_jump:
                enterCaptureActivity();
                break;
            case R.id.history_img_button:
                pickFromGallery();
                break;
        }
    }


    /**
     * 选择图片
     */
    private void pickFromGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_SELECT_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_SELECT_PICTURE:
                    Uri imgUri = data.getData();
                    String realPathFromURI = getRealPathFromURI(imgUri);

                    if (realPathFromURI != null) {
                        Mat imread = Imgcodecs.imread(realPathFromURI);
                        DetectInit(getExternalFilesDir(null).getPath()+"/Uhylab");
                        boolean findFeatures = FindFeatures(imread.getNativeObjAddr());
                        DetectRelease();
                        if (findFeatures) {
                            Intent intent = new Intent(this, ResultActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("IMG_URI", realPathFromURI);
                            bundle.putFloatArray("colors", arrcolor);
                            intent.putExtras(bundle);
                            startActivity(intent);
                            finish();
                        }
                    }else{
                        Log.e("UHPhotoActivity", "realPathFromURI 为空");
                    }


                    break;
            }
        }

    }

    /**
     * 通过图片URI 获得路径
     *
     * @param uri 图片URI
     * @return 路径
     */
    public String getRealPathFromURI(Uri uri) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public native boolean FindFeatures(long matAddrRgba);
    public native void DetectInit(String path);

    public native void DetectRelease();
}
